
var fs = require('node-fs');
var gm = require('gm');
var mkdirp = require('mkdirp');
var request = require('request');
var async = require('async');

var newDownloadHelper = {
	/**
      * 文件下载
      */
    download: function(user_id, media_id, url, type, _store_path, fnCb){
	    var store_path = _store_path; //本地存储目录
        mkdirp.sync(store_path);
     
        var fileType = type == 'mp3' ? '.amr' : (type == 'pic' ? '.jpg' : ('.'+type));
        var filename = media_id+fileType;
        newDownloadHelper.myDownload(url, store_path, filename, function(err){
            if(err){
            	return fnCb(err, "")
            }

            if(filename.indexOf('.amr') != -1){
                filename = filename.substring(0,filename.indexOf('.amr')) + '.mp3';
            }

            return fnCb(0, _store_path+filename);
        });
    },
    // 判断对象的类型
    mytype: function (value){
        var result = Object.prototype.toString.call(value);
        if(!value) return undefined;
        var prefix = '[object ';
        return result.substring(result.indexOf('[')+prefix.length,result.indexOf(']')).toLowerCase();
    },
    //下载方法
    myDownload: function(url, dir, filename, callback){
    	console.log(url);
    	console.log(dir);
    	console.log(filename);

        request({uri:url}, function(err, response, body) {
            //console.log('response',response);
        	var rightFlag = response.statusCode == 200 && !err;
            if(body.errcode){
                console.log(body.errcode);
                console.log(body.errmsg);
            }
            try{
                var filePath = dir + filename;
                console.log('filePath: ' + filePath);
                if (fs.exists(filePath)) {
                    fs.unlinkSync(filePath);
                    console.log('Del file ' + filePath);
                }
                request(url).pipe(fs.createWriteStream(filePath)).on('close', function(){
                    console.log("response close"); 
                    if(filePath.indexOf('.amr') != -1){ // 音频文件
                        var target = dir + newDownloadHelper.getFileName(filename) + ".mp3";
                        console.log("target:", target);
                        child_process.execFile('ffmpeg', ['-i', filePath, target], function(err, result) {
                            console.log("ffmpeg covert amr to mp3, err:", err, " result:", result);
                        });
                    }else if(~filePath.indexOf('.jpg') || ~filePath.indexOf('.png') || ~filePath.indexOf('.jpeg') || ~filePath.indexOf('.gif')){   // 图片文件
                        var target_path = filePath;
                        var thumbnail = target_path.substring(0, target_path.lastIndexOf(".")) + "_thumbnail" + target_path.substring(target_path.lastIndexOf("."));
                        console.log('thumbnail=' + thumbnail);
                        gm(target_path).resize(320).noProfile().write(thumbnail, function(err) {});
                    }
                  }); // 下载文件
            }catch(e){
                console.log(e);
                rightFlag = false;
            }
            callback && callback.call(this,!rightFlag);
        });
    },

}

module.exports = newDownloadHelper;